package download;

import jdk.nashorn.internal.ir.CallNode;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

/**
 * 韩要雷
 *
 * 文件下载：
 * 1.需要通过response.setContType()  设置头字段
 * 2.需要通过response.setHeader() 方法设置头字段的值
 * 3.读取下载文件，需要通过response.getOutputStream()
 */
@WebServlet("/download")
public class DownloadServlet extends HttpServlet {

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        //1.设置字符编码
        req.setCharacterEncoding("UTF-8");

        //2.获取下载的文件名
        String fileName = req.getParameter("fileName");

        //3.判断文件是否为空
        if (fileName == null || "".equals(fileName.trim())) {
            System.out.println("文件名为空");
            return ;
        }
        //4.获取文件的下载路径
        String realPath = req.getServletContext().getRealPath("/");

        //5.通过下载路径获取file对象
        File file = new File(realPath + fileName);

        //6.判断file对象是否为存在，且是否是真实的文件
        if (file.exists() && file.isFile()) {
            //7.需要通过response.setContentType() 设置头字段
            resp.setContentType("application/x-msdownload");
            //8.需要通过response.setHeader() 方法设置头字段的值
            resp.setHeader("Content-Disposition","attachment;filename=" + fileName);
            //9.得到输入流
            FileInputStream in = new FileInputStream(file);
            //10.得到输出流
            ServletOutputStream out = resp.getOutputStream();
            byte[] bytes = new byte[1024];//定义字节数组
            //定义初始化长度
            int len = 0;
            //循环输出
            while ((len = in.read(bytes)) != -1) {
                out.write(bytes,0,len);
            }
            out.close();
            in.close();
        }else {
            System.out.println("文件不存在，下载失败！！！");
        }
    }
}
